package com.example.app3.ui.dashboard;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.app3.R;
import com.example.app3.util.Init;

import java.util.ArrayList;
import java.util.Random;

public class DashboardFragment extends Fragment {


    private static int states = 0;
    private int index = -1;
    private static final int COMPLETED = 0;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);

        TextView textViewID = (TextView) root.findViewById(R.id.textView20);
        ImageView image = root.findViewById(R.id.imageView3);
        Button start = root.findViewById(R.id.button6);
        start.setOnClickListener(v -> {

            states++;
            if (states % 2 == 0) {//停止的语句

                start.setText("开始");


            } else {
                //开始的内容

                ArrayList<Object> imageIds = new ArrayList<Object>();
                //批量获取id
                for (int i = 1; i < 8; i++) {
                    int id = getResources().getIdentifier("head" + i, "drawable", "com.example.app3");

                    imageIds.add(id);
                }

                //初始化人名
                ArrayList<String> texts = Init.initDianMing();


                //-----------UI线程更改------------------------
                Handler handler = new Handler(msg -> {
                    if (msg.what == COMPLETED) {
                        textViewID.setText(texts.get(index).toString());
                        image.setImageResource((Integer) imageIds.get(index));

                    }
                    return true;
                });

                //-----------设置额外线程-----------------------
                new Thread(() -> {
                    Random r = new Random();

                    for (int i = 0; i < texts.size() * 5; i++) {
                        index = r.nextInt(texts.size());

                        //处理完成后给handler发送消息  
                        Message msg = new Message();
                        msg.what = COMPLETED;
                        handler.sendMessage(msg);
                        try {
                            Thread.currentThread().sleep(150);//毫秒
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                start.setText("就是你了");


            }

        });

        return root;
    }
}